package com.team3.ecommerce.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.sun.org.apache.xpath.internal.operations.Mod;
import com.team3.ecommerce.domain.*;
import com.team3.ecommerce.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.jws.WebParam;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private UserAuthService userAuthService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private ShoppingCartService shoppingCartService;


    @GetMapping("/orderConfirm")
    public String orderConfirm(Model model, Principal principal, @RequestParam(value = "commUid", required = false) String commUid) {
        if (commUid != null) {
            String userUid = userAuthService.findUserByPrincipal(principal).getUserUid();
            UserInfo userInfo = userInfoService.getUserInfo(userUid);
            model.addAttribute("userInfo", userInfo);
            List<Commodity> commodityList = new ArrayList<>();
            Commodity commodity = commodityService.findCommodityById(commUid);
            commodityList.add(commodity);
            float[] priceList = new float[1];
            priceList[0] = commodity.getCommPrice();
            float cartTotalPrice = commodity.getCommPrice();
            List<ShoppingCartItem> shoppingCartItemList = new ArrayList<>();
            ShoppingCartItem shoppingCartItem = new ShoppingCartItem();
            shoppingCartItem.setCommQuantity(1);
            shoppingCartItemList.add(shoppingCartItem);
            model.addAttribute("commodityList", commodityList);
            model.addAttribute("shoppingCartItemList", shoppingCartItemList);
            model.addAttribute("priceList", priceList);
            model.addAttribute("cartTotalPrice", cartTotalPrice);
            model.addAttribute("buyNow", "true");
            return "orderConfirm.html";
        }

        String userUid = userAuthService.findUserByPrincipal(principal).getUserUid();
        UserInfo userInfo = userInfoService.getUserInfo(userUid);
        model.addAttribute("userInfo", userInfo);
        List<ShoppingCartItem> shoppingCartItemList = shoppingCartService.getUserShoppingCart(userUid);
        for (int i = 0; i < shoppingCartItemList.size(); i++) {
            if (shoppingCartItemList.get(i).getItemChecked().equals("false")) {
                shoppingCartItemList.remove(i);
                i--;
            }
        }
        List<Commodity> commodityList = new ArrayList<>();
        float[] priceList = new float[shoppingCartItemList.size()];
        float cartTotalPrice = 0;//购物车总价格计算
        for (int i = 0; i < shoppingCartItemList.size(); i++) {
            commodityList.add(commodityService.findCommodityById(shoppingCartItemList.get(i).getCommUid()));
            priceList[i] = commodityList.get(i).getCommPrice() * shoppingCartItemList.get(i).getCommQuantity();
            cartTotalPrice += priceList[i];
        }
        model.addAttribute("commodityList", commodityList);
        model.addAttribute("shoppingCartItemList", shoppingCartItemList);
        model.addAttribute("priceList", priceList);
        model.addAttribute("cartTotalPrice", cartTotalPrice);
        return "orderConfirm.html";
    }

    @PostMapping("/orderConfirm")
    public String makeNewOrder(String commUid, UserInfo userInfo, Principal principal) {
        if (commUid != null) {
            userInfo.setUserUid(userAuthService.findUserByPrincipal(principal).getUserUid());
            Order newOrder = orderService.newOrder(userInfo);
            orderService.insertCommodity(newOrder.getOrderUid(), commUid, 1);
            return "redirect:/order/" + newOrder.getOrderUid();
        }
        userInfo.setUserUid(userAuthService.findUserByPrincipal(principal).getUserUid());
        Order newOrder = orderService.makeNewOrderFromCart(userInfo);
        shoppingCartService.cleanUserShoppingCart(userInfo.getUserUid());
        return "redirect:/order/" + newOrder.getOrderUid();
    }

    @RequestMapping("/order/{id}")
    public String showOrder(Model model, @PathVariable("id") String id,Principal principal) {
        Order order = orderService.getOrder(id);
        if(!order.getUserUid().equals(userAuthService.findUserByPrincipal(principal).getUserUid()))
            return "redirect:/userCenter/myOrders?page=1";
        List<CommInOrder> commInOrderList = orderService.getCommListInOrder(id);
        List<Commodity> commodityList = new ArrayList<>();
        commodityList.clear();
        for (int i = 0; i < commInOrderList.size(); i++) {
            Commodity com = commodityService.findCommodityById(commInOrderList.get(i).getCommUid());
            commodityList.add(com);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss 秒");
        String placeTime = sdf.format(order.getOrderPlaceTime());
        String paymentTime = sdf.format(order.getOrderPaymentTime());
        float[] priceList = new float[commInOrderList.size()];//计算每个商品的单行总价
        for (int i = 0; i < commInOrderList.size(); i++) {
            priceList[i] = commInOrderList.get(i).getCommQuantity() * commInOrderList.get(i).getCommPrice();
        }
        String orderStatusZh = order.getOrderStatus();
        orderStatusZh = orderStatusZh.replace("placed", "等待支付");
        orderStatusZh = orderStatusZh.replace("unpaid", "等待支付");
        orderStatusZh = orderStatusZh.replace("paid", "等待发货");
        orderStatusZh = orderStatusZh.replace("shipping", "已发货");
        model.addAttribute("orderStatusZh", orderStatusZh);
        model.addAttribute("order", order);
        model.addAttribute("commodityList", commodityList);
        model.addAttribute("commInOrderList", commInOrderList);
        model.addAttribute("priceList", priceList);
        model.addAttribute("placeTime", placeTime);
        model.addAttribute("paymentTime", paymentTime);
        return "orderDetails.html";
    }


    @RequestMapping("/order/pay/{orderUid}")//使用支付宝付款
    public ModelAndView payOrder(Model model, @PathVariable("orderUid") String order_uid, HttpServletResponse httpResponse) throws ServletException, IOException {
        httpResponse.setContentType("text/html;charset=UTF-8");
        httpResponse.getWriter().write(orderService.getPaymentPage(order_uid, "http://localhost:8280/order/" + order_uid));//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
        return null;
    }


}